package NIO;

import com.sun.xml.internal.ws.addressing.WsaTubeHelperImpl;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static NIO.ByteBufferUtil.debugRead;

public class BlockingServer {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer=ByteBuffer.allocate(16);

        //create the server
        ServerSocketChannel ssc=ServerSocketChannel.open();

        //bind the port
        ssc.bind(new InetSocketAddress(8080));

        List<SocketChannel> list=new ArrayList<>();

        while (true){
            System.out.println("connnecting");

            SocketChannel accept = ssc.accept();//blocking
            System.out.println("connected:"+accept);
            list.add(accept);
            for (SocketChannel sc:list){
                System.out.println("before read:"+sc);
                sc.read(buffer);
                buffer.flip(); //切换成读模式
                debugRead(buffer);
                buffer.clear();
                System.out.println("After read:"+sc);
            }

        }
    }
}
